from django.db import models
from django.conf import settings

class Snapshot(models.Model):
    """Stores information about a nightly snapshot"""
    snapshot_time = models.DateTimeField("Snapshot Time", auto_now_add=True, db_index=True)
    filehash = models.CharField("File Hash (md5)", maxlength=32)
    filename = models.FileField("Snapshot Filename", upload_to=settings.NIGHTLY['project']+'/%Y/%m/%d')
    filesize = models.PositiveIntegerField("Snapshot Filesize")
    revision = models.CharField("Snapshot's Current Revision", maxlength=32)
    
    # Note that we store a count of the Log entries for this Snapshot. This is badly normalised
    # BUT means that we can do a whole lot less queries in our generic views. 
    changes = models.PositiveIntegerField("Number of Changes in this snapshot", default=0)
    
    def __str__(self):
        return '%s [%s] %s' % (settings.NIGHTLY['project'], self.revision, self.snapshot_time)

    def get_absolute_url(self):
        """Returns the absolute URL to this FILE"""
        return  '%(media_url)s/%(year)s/%(month)s/%(filename)s' % {
                'media_url':settings.MEDIA_URL,
                'project':settings.NIGHTLY['project'],
                'year': self.snapshot_time.strftime("%Y"),
                'month': self.snapshot_time.strftime("%m"),
                'day': self.snapshot_time.strftime("%d"),
                'filename': self.filename,
        }
        
    class Admin:
        date_hierarchy = 'snapshot_time'
        list_display = ( 'revision', 'filename', 'filehash', 'snapshot_time' )
        
class Log(models.Model):
    """Stores subversion log information for each Snapshot"""
    snapshot = models.ForeignKey(Snapshot)
    revision = models.CharField("Revision", maxlength=32)
    author = models.CharField("Author", maxlength=32)
    rdate = models.DateTimeField("Change Time")
    msg = models.TextField("Message")    
    
    def __str__(self):
        return '%s:%s %s...' % (self.snapshot, self.revision, self.msg[0:25])
        
    class Admin:
        date_hierarchy = 'rdate'
        list_display = ( 'snapshot', 'revision', 'author', 'msg' )
    